package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.contrarywind.adapter.WheelAdapter;
import com.contrarywind.listener.OnItemSelectedListener;
import com.contrarywind.view.WheelView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityWorkDayCalculateBinding;
import stark.common.basic.event.EventStatProxy;

public class WorkDayCalculateActivity extends BaseAc<ActivityWorkDayCalculateBinding> {

    private Dialog mySelDateDialog;
    private WheelView wheelView1, wheelView2, wheelView3;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
    private int type;


    @Override
    protected int onCreate() {
        return R.layout.activity_work_day_calculate;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivWorkDayCalculateBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.llDay.setOnClickListener(this);
        mDataBinding.llTimeFrame.setOnClickListener(this);
        mDataBinding.tvStartDate1.setOnClickListener(this);
        mDataBinding.tvEndDate.setOnClickListener(this);
        mDataBinding.tvStartDate2.setOnClickListener(this);
        mDataBinding.tvWorkDayCalculate.setOnClickListener(this);
        mDataBinding.tvTimeFrameCalculate.setOnClickListener(this);

        //选择日期弹框
        selDateDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.llDay:
                clearSelection();
                mDataBinding.llDay.setBackgroundColor(Color.parseColor("#FFC1C1"));
                mDataBinding.tvWorkDay1.setTextColor(Color.parseColor("#FF4E4E"));
                mDataBinding.tvTimeFrame1.setTextColor(Color.parseColor("#FF4E4E"));
                mDataBinding.ivImg1.setImageResource(R.drawable.arr2);
                mDataBinding.llDayFunc.setVisibility(View.VISIBLE);
                break;
            case R.id.llTimeFrame:
                clearSelection();
                mDataBinding.llTimeFrame.setBackgroundColor(Color.parseColor("#FFC1C1"));
                mDataBinding.tvWorkDay2.setTextColor(Color.parseColor("#FF4E4E"));
                mDataBinding.tvTimeFrame2.setTextColor(Color.parseColor("#FF4E4E"));
                mDataBinding.ivImg2.setImageResource(R.drawable.arr2);
                mDataBinding.llTimeFrameFunc.setVisibility(View.VISIBLE);
                break;
            case R.id.tvStartDate1://计算工作天数开始日期
                type = 0;
                mySelDateDialog.show();
                break;
            case R.id.tvEndDate://计算工作天数结束日期
                type = 1;
                mySelDateDialog.show();
                break;
            case R.id.tvStartDate2://计算时段开始日期
                type = 2;
                mySelDateDialog.show();
                break;
            case R.id.tvWorkDayCalculate://工作天数计算
                calculateWorkDay();
                break;
            case R.id.tvTimeFrameCalculate://时段计算
                calculateTimeFrame();
                break;
            //选择日期弹框
            case R.id.tvDialogSelDateCancel://取消
                mySelDateDialog.dismiss();
                break;
            case R.id.tvDialogSelDateRight://确定
                mySelDateDialog.dismiss();
                int year = wheelView1.getCurrentItem() + 1980;
                int moon = wheelView2.getCurrentItem() + 1;
                int day = wheelView3.getCurrentItem() + 1;
                String selDate = year + "年" + (moon < 10 ? "0" + moon : moon) + "月" + (day < 10 ? "0" + day : day + "日");
                if (type == 0) {
                    mDataBinding.tvStartDate1.setText(selDate);
                } else {
                    mDataBinding.tvEndDate.setText(selDate);
                }
                if (type == 2) {
                    mDataBinding.tvStartDate2.setText(selDate);
                }
                break;
        }
    }

    @Override
    protected void initData() {

    }

    private void calculateWorkDay() {
        String startDate = mDataBinding.tvStartDate1.getText().toString();
        if (TextUtils.isEmpty(startDate)) {
            ToastUtils.showShort(getString(R.string.please_sel_start_date));
            return;
        }
        String endDate = mDataBinding.tvEndDate.getText().toString();
        if (TextUtils.isEmpty(endDate)) {
            ToastUtils.showShort(getString(R.string.please_sel_end_date));
            return;
        }
        long startTime = TimeUtils.string2Millis(startDate, new SimpleDateFormat("yyyy年MM月dd日"));
        long endTime = TimeUtils.string2Millis(endDate, new SimpleDateFormat("yyyy年MM月dd日"));

        //毫秒ms
        long diff = endTime - startTime;

        long diffDays = diff / (24 * 60 * 60 * 1000);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(startTime);
        int weekdays = 0;
        while (calendar.getTime().getTime() < endTime) {
            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            // 如果是周末，则跳过
            if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
                calendar.add(Calendar.DATE, 1);
                continue;
            }
            weekdays++;
            calendar.add(Calendar.DATE, 1);
        }

        mDataBinding.tvWorkDay.setText(String.valueOf(weekdays));
        mDataBinding.tvTotalDay.setText(String.valueOf(diffDays));
        mDataBinding.tvWeekendDay.setText(String.valueOf(diffDays - weekdays));
    }

    private void calculateTimeFrame() {
        String startDate = mDataBinding.tvStartDate2.getText().toString();
        if (TextUtils.isEmpty(startDate)) {
            ToastUtils.showShort(getString(R.string.please_sel_start_date));
            return;
        }
        String str = mDataBinding.etNum.getText().toString();
        if (TextUtils.isEmpty(str)) {
            ToastUtils.showShort(getString(R.string.please_input_day_num));
            return;
        }
        int num = Integer.parseInt(str);
        long startTime = TimeUtils.string2Millis(startDate, new SimpleDateFormat("yyyy年MM月dd日"));

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(startTime);
        int weekdays = 0;
        for (int i = 0; i < num; i++) {
            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            // 如果是周末，则跳过
            if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
                i--;
            }
            calendar.add(Calendar.DATE, 1);
        }

        mDataBinding.tvResult.setText(TimeUtils.date2String(calendar.getTime(), new SimpleDateFormat("yyyy-MM-dd")));
    }

    //选择日期弹框
    private void selDateDialog() {
        mySelDateDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_date, null);
        mySelDateDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mySelDateDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        lp.width = (int) (dm.widthPixels * 1);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogSelDateCancel);
        TextView dialogRight = inflate.findViewById(R.id.tvDialogSelDateRight);
        wheelView1 = inflate.findViewById(R.id.wheel_view1);
        wheelView2 = inflate.findViewById(R.id.wheel_view2);
        wheelView3 = inflate.findViewById(R.id.wheel_view3);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
        wheelView1.setDividerColor(Color.parseColor("#FFFFFF"));
        wheelView1.setTextColorCenter(Color.parseColor("#0095FF"));
        wheelView1.setLineSpacingMultiplier(2.5f);
        wheelView1.setDividerType(WheelView.DividerType.WRAP);
        wheelView1.setCurrentItem(43);
        wheelView1.setItemsVisibleCount(5);
        wheelView1.setCyclic(true);
        wheelView1.setTextSize(18);
        wheelView2.setDividerColor(Color.parseColor("#FFFFFF"));
        wheelView2.setTextColorCenter(Color.parseColor("#0095FF"));
        wheelView2.setLineSpacingMultiplier(2.5f);
        wheelView2.setDividerType(WheelView.DividerType.WRAP);
        wheelView2.setCurrentItem(0);
        wheelView2.setItemsVisibleCount(5);
        wheelView2.setCyclic(true);
        wheelView2.setTextSize(18);
        wheelView3.setDividerColor(Color.parseColor("#FFFFFF"));
        wheelView3.setTextColorCenter(Color.parseColor("#0095FF"));
        wheelView3.setLineSpacingMultiplier(2.5f);
        wheelView3.setDividerType(WheelView.DividerType.WRAP);
        wheelView3.setCurrentItem(0);
        wheelView3.setItemsVisibleCount(5);
        wheelView3.setCyclic(true);
        wheelView3.setTextSize(18);
        //设置滚轮数据
        List<String> listYear = new ArrayList<>();//年 1980-2040
        for (int i = 0; i < 61; i++) {
            listYear.add(String.valueOf(1980 + i));
        }
        List<String> listMonth = new ArrayList<>();//月 12
        for (int i = 0; i < 12; i++) {
            listMonth.add(String.valueOf((i + 1) < 10 ? "0" + (i + 1) : i + 1));
        }
        WheelAdapter adapter1 = new ArrayWheelAdapter(listYear);
        wheelView1.setAdapter(adapter1);
        WheelAdapter adapter2 = new ArrayWheelAdapter(listMonth);
        wheelView2.setAdapter(adapter2);
        setDayDate(31);//日 默认显示1月 共31天

        //监听月份滚动选择
        wheelView2.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                index = index + 1;
                if (index == 1 || index == 3 || index == 5 || index == 7 || index == 8 || index == 10 || index == 12) {
                    //大月31天
                    setDayDate(31);
                } else if (index == 2) {
                    //2月判断是闰(29)还是平(28)
                    if (TimeUtils.isLeapYear(TimeUtils.getNowString(format), format)) {
                        setDayDate(29);
                    } else {
                        setDayDate(28);
                    }
                } else {
                    //小月30天
                    setDayDate(30);
                }
            }
        });
        //滚动到对应日期
        String date = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
        String[] split = date.split("-");
        int year = Integer.parseInt(split[0]);//年
        int moon = Integer.parseInt(split[1]);//月
        int day = Integer.parseInt(split[2]);//日
        wheelView1.setCurrentItem(year - 1980);
        wheelView2.setCurrentItem(moon - 1);
        wheelView3.setCurrentItem(day - 1);
    }


    //设置天
    private void setDayDate(int num) {
        List<String> listDay = new ArrayList<>();//日 默认显示1月31天
        for (int i = 0; i < num; i++) {
            listDay.add(String.valueOf((i + 1) < 10 ? "0" + (i + 1) : i + 1));
        }
        WheelAdapter adapter3 = new ArrayWheelAdapter(listDay);
        wheelView3.setAdapter(adapter3);
    }

    private void clearSelection() {
        mDataBinding.llDay.setBackgroundColor(Color.parseColor("#EFEFEF"));
        mDataBinding.tvWorkDay1.setTextColor(Color.parseColor("#BEBEBE"));
        mDataBinding.tvTimeFrame1.setTextColor(Color.parseColor("#BEBEBE"));
        mDataBinding.ivImg1.setImageResource(R.drawable.arrw);
        mDataBinding.llDayFunc.setVisibility(View.GONE);
        mDataBinding.llTimeFrame.setBackgroundColor(Color.parseColor("#EFEFEF"));
        mDataBinding.tvWorkDay2.setTextColor(Color.parseColor("#BEBEBE"));
        mDataBinding.tvTimeFrame2.setTextColor(Color.parseColor("#BEBEBE"));
        mDataBinding.ivImg2.setImageResource(R.drawable.arrw);
        mDataBinding.llTimeFrameFunc.setVisibility(View.GONE);
    }

}